package com.mdx.rest.base;
import com.mdx.api.util.ResultVo;
import com.mdx.tools.util.StringUtils;
import com.mdx.tools.util.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends BaseController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@ExceptionHandler(value = BusinessException.class)
	@ResponseBody
	public ResultVo handle(Exception e){
		if(e instanceof BusinessException){
			logger.error("业务日志",e);
			BusinessException myException = (BusinessException) e;
			return  ResultVo.error(myException.getMessage(),myException.getData());
		}
		logger.error("系统日志",e);
		return ResultVo.error("1000","业务繁忙");
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ResultVo baseErrorHandler(Exception e) throws Exception {
		logger.error(e.getMessage(),e);
		e.printStackTrace();
		return  ResultVo.error("服务器异常");
	}

	@ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
	@ResponseBody
	public ResultVo MethodArgumentTypeMismatchExceptionExceptionHandler(MethodArgumentTypeMismatchException e) throws Exception {
		logger.error(e.getMessage(),e);
		return  ResultVo.error("参数错误");
	}

	@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
	@ResponseBody
	public ResultVo httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e) throws Exception {
		logger.error(e.getMessage(),e);
		return  ResultVo.error("请求方式不正确");
	}


	@ExceptionHandler(value = BindException.class)
	@ResponseBody
	public ResultVo bindErrorHandler(BindException e) throws Exception {
		logger.error(e.getMessage(),e);
		return  ResultVo.error(StringUtils.isContainChinese(e.getAllErrors().get(0).getDefaultMessage())?e.getAllErrors().get(0).getDefaultMessage():"参数错误");
	}

}
